package battleship;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class NewOpenGamesServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // get new open games when they are created (a user opens a game)
        System.out.println("NewOpenGamesServlet: starting");
    	String userToken= request.getParameter("token");
    	int id= (Integer) UserIdTokenHashMap.idTokenMap.get(userToken);
     //   int id = Integer.parseInt(request.getParameter("id"));
        User user = Context.users[id];

        Game game = new Game();
        try {
            game = user.newOpenGames.take();
            if (!user.online) {
                return;
            }
        } catch (InterruptedException e) {
            System.out.println("NewOpenGamesServlet InterruptedException: " + e.getMessage());
        }
        int playerID = game.player1ID;
        User player = Context.users[playerID];
        String username = player.username;
        String reply = " { \"id\": \"" + playerID + "\", \"username\": \"" + username + "\" } ";

        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.print(reply);
        out.close();
        System.out.println(user.username + "'s newOpenGamesServlet: a user opened a game: " + username);
        System.out.println("NewOpenGamesServlet: finished");
    }
}